package shuishijie.suishijie;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;

import java.lang.ref.SoftReference;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import shuishijie.suishijie.fragment.OrderPayFragment;
import shuishijie.suishijie.model.AlipayInfo;
import shuishijie.suishijie.model.GloblaData;
import shuishijie.suishijie.model.GvgModel;
import shuishijie.suishijie.model.OrderInfo;
import shuishijie.suishijie.model.ProfitInfo;
import shuishijie.suishijie.model.WechartPay;
import shuishijie.suishijie.model.web.BaseResponse;
import shuishijie.suishijie.model.web.RxSubscriber;
import shuishijie.suishijie.util.AppUtil;
import shuishijie.suishijie.util.WechartUtil;
import shuishijie.suishijie.view.PasswordInputPopup;
import shuishijie.suishijie.view.ViewSettingItem;
import shuishijie.suishijie.view.WebBrowseActivity;

public class PayActivity extends BaseActivity {

    @BindView(R.id.order_num)
    ViewSettingItem orderNum;
    @BindView(R.id.price)
    ViewSettingItem price;
    @BindView(R.id.balance_pay_text)
    TextView balancePayText;
    @BindView(R.id.friend_pay_text)
    TextView friendPayText;
    @BindView(R.id.wechart)
    RadioButton wechart;
    @BindView(R.id.alipay)
    RadioButton alipay;
    @BindView(R.id.unionpay)
    RadioButton unionpay;
    @BindView(R.id.balance_pay)
    RadioButton balancePay;
    @BindView(R.id.friend_pay)
    RadioButton friendPay;
    @BindView(R.id.pay_type)
    RadioGroup payType;
    @BindView(R.id.pay)
    Button pay;
    private OrderInfo orderInfo;
    public static final int ALI_PAY_FLAG = 0;
    PasswordInputPopup popup;
    private String orderid;
    private String user_id;
    private String mobile;
    private String token;
    private double b;
    MyHandler mHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_order_pay);
        ButterKnife.bind(this);
        mHandler = new MyHandler(PayActivity.this);
       // WechartUtil.getInstance().regTowWx(PayActivity.this);
        token=getIntent().getStringExtra("token");
        mobile=getIntent().getStringExtra("mobile");
        orderid=getIntent().getStringExtra("orderid");
        user_id=getIntent().getStringExtra("user_id");

        GvgModel.getInstance().showIncome(mobile,token,user_id,orderid)
                .subscribe(new RxSubscriber<BaseResponse<ProfitInfo>>(this, res -> {
                    balancePayText.setText("余额支付(可用余额" + AppUtil.getMoneyStr(res.data.availableMoney) + ")");
                    b=res.data.totalPrice;
                    orderNum.setText("订单编号: "+res.data.orderId);
                    price.setText("应付金额: "+AppUtil.getMoneyStr(res.data.totalPrice));
                   if (res.data.availableMoney >= b) {
                        balancePay.setEnabled(true);

                    }
                }));


    }


    public class MyHandler extends Handler {
        SoftReference<PayActivity> fragmentSoftReference;

        public MyHandler(PayActivity fragment) {
            this.fragmentSoftReference = new SoftReference<PayActivity>(fragment);
        }
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ALI_PAY_FLAG:
                    Map<String, String> result = (Map<String, String>) (msg.obj);
                    if (result != null && fragmentSoftReference.get() != null) {
                        int status = AppUtil.parseInt("" + result.get("resultStatus"));
                        String tostMsg = result.get("memo");

                        if (status == 9000) {
                            tostMsg = "支付成功";
                            showMessage("支付成功");
   //                         Intent intent =new Intent(PayActivity.this,WebViewActivity.class);
//                            intent.putExtra("type","1");
//                            intent.putExtra("url","https://offline.gvg666.com/dist/index.html#/load/allOrders");
//                            startActivity(intent);
//                            finish();
                        }
                        // Toast.makeText(fragmentSoftReference.get().getContext(), tostMsg, Toast.LENGTH_LONG).show();
                        if (status == 9000) {
                            Intent intent =new Intent(PayActivity.this,WebBrowseActivity.class);
                            intent.putExtra("type","1");
                            intent.putExtra("url","https://offline.gvg666.com/dist/index.html#/load/allOrders");
                            startActivity(intent);
                            finish();
                             //finish();
                        }
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    }
    @OnClick(R.id.pay)
    public void onViewClicked() {
        if (alipay.isChecked()) {
            alipay();
        } else if (wechart.isChecked()) {
            wechart();
        } else if (balancePay.isChecked()) {
            popup = new PasswordInputPopup(PayActivity.this, b);
            popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            popup.setListener(p -> {
                banlancePay(p);
            });
            popup.show(pay, Gravity.BOTTOM, 0, 0);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
//        String str = data.getExtras().getString("pay_result");
//        if (str.equalsIgnoreCase("success")) {
//            // 支付成功后，extra中如果存在result_data，取出校验
//            // result_data结构见c）result_data参数说明
//            if (data.hasExtra("result_data")) {
//                String sign = data.getExtras().getString("result_data");
//                // 验签证书同后台验签证书
//                // 此处的verify，商户需送去商户后台做验签
////                if (verify(sign)) {
//                //验证通过后，显示支付结果
//                  showMessage(" 支付成功！ ");
////                } else {
//                // 验证不通过后的处理
//                // 建议通过商户后台查询支付结果
////                }
//            } else {
//                // 未收到签名信息
//                // 建议通过商户后台查询支付结果
//            }
//           finish();
//        } else if (str.equalsIgnoreCase("fail")) {
//            showMessage(" 支付失败！ ");
//        } else if (str.equalsIgnoreCase("cancel")) {
//             showMessage(" 你已取消了本次订单的支付！ ");
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void banlancePay(String p) {
        GvgModel.getInstance().availablePay("" + orderid, p,mobile,token,user_id)
                .subscribe(new RxSubscriber<BaseResponse<Object>>(this, res -> {
                        showMessage("支付成功");
                    if (popup != null) {
                        popup.dismiss();
                    }
                    Intent intent =new Intent(PayActivity.this,WebBrowseActivity.class);
                    intent.putExtra("type","1");
                   intent.putExtra("url","https://offline.gvg666.com/dist/index.html#/load/allOrders");
                    startActivity(intent);
                     finish();
                }));
    }

    private void wechart() {

        GvgModel.getInstance().wxPay(mobile,token,user_id,orderid)
                .subscribe(new RxSubscriber<BaseResponse<WechartPay>>(this, res -> {
                    GloblaData.setWechartPay(1);
                    WechartUtil.getInstance().pay(res.data);
                    //finish();
//                    Intent intent =new Intent(PayActivity.this,WebViewActivity.class);
//                    intent.putExtra("type","1");
//                    intent.putExtra("url","https://offline.gvg666.com/dist/index.html#/load/allOrders");
//                    startActivity(intent);
//                    finish();
                }));
    }

    private void alipay() {
        GvgModel.getInstance().alipayPay(mobile,token,user_id,orderid)
                .subscribe((Observer<? super BaseResponse<AlipayInfo>>) new RxSubscriber<BaseResponse<AlipayInfo>>(this, res -> {
                    new Thread(() -> {
                        PayTask alipay = new PayTask(PayActivity.this);
                        Map<String, String> result = alipay.payV2(res.data.orderInfo, true);

                        Message msg = new Message();
                        msg.what = ALI_PAY_FLAG;
                        msg.obj = result;
                        Log.e("QQQQ",result.toString());
                      ///  if(msg!=null)
                       // {
                            mHandler.sendMessage(msg);
                       // }

//                        Intent intent =new Intent(PayActivity.this,WebViewActivity.class);
//                        intent.putExtra("type","1");
//                        intent.putExtra("url","https://offline.gvg666.com/dist/index.html#/load/allOrders");
//                        startActivity(intent);
//                        finish();
                    }).start();
                }));
    }
}
